package cn.wei.sdd.core.controller.wx;

import cn.wei.common.exception.Assert;
import cn.wei.common.result.R;
import cn.wei.common.result.ResponseEnum;
import cn.wei.common.utils.RegexValidateUtils;
import cn.wei.sdd.base.util.JwtUtils;
import cn.wei.sdd.core.pojo.entity.User;
import cn.wei.sdd.core.pojo.vo.*;
import cn.wei.sdd.core.service.UserService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


/**
 * Created with IntelliJ IDEA.
 *
 * @Author: wei
 * @Date: 2021/10/14/16:23
 */
@RestController
@Api(tags = "微信用户管理")
@RequestMapping(value = "/wxApi/core/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    //wx
    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @ApiOperation("判断是否普通用户")
    @GetMapping("isUser")
    public Boolean isUser(HttpServletRequest request){
        String token = request.getHeader("token");
        int userType = Integer.parseInt(JwtUtils.getUserType(token));
        System.out.println(userType);
        return  userType== User.USER?true:false;


    }
    @ApiOperation("绑定手机号")
    @GetMapping("bingMobile/{mobile}/{code}")
    public R bingMobile(
            @PathVariable("mobile") String mobile,
            @PathVariable("code") String code,
            HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);

        //手机不能为空
        Assert.notEmpty(mobile,ResponseEnum.MOBILE_NULL_ERROR);

        //验证码不能为空
        Assert.notEmpty(code,ResponseEnum.CODE_NULL_ERROR);

        //验证码是否正确
        String checkCode = String.valueOf(redisTemplate.opsForValue().get("sdd:sms:code:" + mobile));
        Assert.equals(code,checkCode,ResponseEnum.CODE_ERROR);

        userService.bingMobile(mobile,userId,code);

        return R.ok().message("绑定手机成功");
    }


    @ApiOperation("获取用户首页信息")
    @GetMapping("getUserIndexInfo/")
    public R getUserIndexInfo(
            HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        Integer userType = Integer.parseInt(JwtUtils.getUserType(token));
        UserIndexInfoVO userIndexInfo = userService.getUserIndexInfo(userType,userId);
        return R.ok().data("info",userIndexInfo);
    }
    @ApiOperation("验证token是否有效")
    @GetMapping("checkToken")
    public boolean checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        return JwtUtils.checkToken(token);
    }

    @PostMapping("/login")
    @ApiOperation("wx普通用户登录")
    public R Login(@RequestBody WxLoginVO wxLoginVo){
        String url= "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+wxLoginVo.getCode()+"&grant_type=authorization_code";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(response.isSuccessful()){
            String res = null;
            try {
                res = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }

            JSONObject jsonObject = JSONObject.parseObject(res);

            String session_key = jsonObject.getString("session_key");
            String openid =jsonObject.getString("openid");
            System.out.println(res);
            System.out.println(session_key);
            System.out.println(openid);


            if (openid!=null){
                String token = "";
                String message = "";
                //判断openid是否存在
                Boolean b = userService.selectUserByOpenid(openid);


                if (!b){
                    userService.addWxUser(openid);
                    token = userService.getToken(openid);
                    message="新用户";

                }
                else{
                    message="用户已存在";
                    token = userService.getToken(openid);

                }
                Map<String, Object> map = new HashMap<>();
                map.put("token",token);
                map.put("userType",User.USER);

                return R.ok().data(map).message(message);
            }
            return R.ok().message("登录失败");


        }

        System.out.println(wxLoginVo);
        return R.ok().message("登录失败");

    }

    @PostMapping("/updateInfo")
    @ApiOperation("更新wx用户信息")
    public R updataUserInfo(@RequestBody UserVO userVo, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);

        userService.updateInfo(userVo,userId);
        return R.ok().message("updateInfo:success!");
    }

    @ApiOperation("获取手机号")
    @GetMapping("getMobile")
    public R getMobileByUserid(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        //获取手机号
        String mobile = userService.getMobileByUserid(userId);
        return R.ok().data("mobile",mobile);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public R getUserInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        UserVO userVo = userService.getInfo(userId);

        return R.ok().data("info",userVo);

    }

    @ApiOperation("判断手机号码是否已经存在")
    @GetMapping("checkMobile/{mobile}")
    public Boolean checkMobile(
            @ApiParam(value = "手机号",required = true)
            @PathVariable String mobile){
        System.out.println(mobile);

       return userService.checkMobile(mobile);

    }

    @ApiOperation("回收员登录")
    @PostMapping("recyclerLogin")
    public R recyclerLogin(@RequestBody LoginVO loginVO){
        String mobile = loginVO.getUserName();
        String password = loginVO.getPassword();

        Assert.notEmpty(mobile,ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(password,ResponseEnum.PASSWORD_NULL_ERROR);

        UserInfoVO userInfoVO = userService.recyclerLogin(loginVO);

        return R.ok().data("userInfo",userInfoVO).message("登录成功");
    }


    @ApiOperation("回收员注册申请")
    @PostMapping("register")
    public R register(
                    @RequestBody
                    @ApiParam(value = "回收员注册对象",required = true)
                            RegisterVO registerVO){
        //手机号码不能为空
        Assert.notEmpty(registerVO.getMobile(), ResponseEnum.MOBILE_NULL_ERROR);

        //检验手机号是否注册
        Boolean res = userService.checkMobile(registerVO.getMobile());
        Assert.isTrue(res==false, ResponseEnum.MOBILE_EXIST_ERROR);

        //姓名不能为空
        Assert.notEmpty(registerVO.getUserName(),ResponseEnum.ACCOUNT_NULL_ERROR);

        //身份证号不能为空
        Assert.notEmpty(registerVO.getIdCard(),ResponseEnum.ID_CARD_NULL_ERROR);



        // 验证码不能为空
        Assert.notEmpty(registerVO.getCode(),ResponseEnum.CODE_NULL_ERROR);

        //身份证正面不能为空
        Assert.notEmpty(registerVO.getIdCard1(),ResponseEnum.ID_CARD_FRONT_NULL_ERROR);

        //身份证反面不能为空
        Assert.notEmpty(registerVO.getIdCard2(),ResponseEnum.ID_CARD_BACK_NULL_ERROR);

        //是否是合法的手机号码
        Assert.isTrue(RegexValidateUtils.checkCellphone(registerVO.getMobile()),ResponseEnum.MOBILE_ERROR);



        //验证码是否正确
        String checkCode = (String) redisTemplate.opsForValue().get("sdd:sms:code:" + registerVO.getMobile());
        Assert.equals(registerVO.getCode(),checkCode,ResponseEnum.CODE_ERROR);


        userService.register(registerVO);
        return R.ok().message("提交申请成功");


    }

    @ApiOperation("获取回收员提成率")
    @GetMapping("percent")
    public R getPercent(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        BigDecimal percent = userService.getPercentByUserId(userId);
        return R.ok().data("percent",percent);

    }




}
